import { corsHeaders } from '../utils/cors'
import { authenticate } from '../utils/crypto'
import { NoteModel } from '../models/note'

export const noteHandler = {
  async list(request, env) {
    const authError = await authenticate(request, env)
    if (authError) return authError

    try {
      const { email } = request.query
      const notes = await NoteModel.findByUser(env, email)
      
      return new Response(JSON.stringify(notes), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    } catch (error) {
      return new Response(JSON.stringify({ error: '获取记事本列表失败' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    }
  },

  async create(request, env) {
    const authError = await authenticate(request, env)
    if (authError) return authError

    try {
      const data = await request.json()
      const result = await NoteModel.create(env, data)
      
      return new Response(JSON.stringify(result), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    } catch (error) {
      return new Response(JSON.stringify({ error: '创建记事本失败' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    }
  },

  async update(request, env) {
    const authError = await authenticate(request, env)
    if (authError) return authError

    try {
      const { id } = request.params
      const data = await request.json()
      const result = await NoteModel.update(env, id, data)
      
      return new Response(JSON.stringify(result), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    } catch (error) {
      return new Response(JSON.stringify({ error: '更新记事本失败' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    }
  },

  async delete(request, env) {
    const authError = await authenticate(request, env)
    if (authError) return authError

    try {
      const { id } = request.params
      await NoteModel.delete(env, id)
      
      return new Response(JSON.stringify({ message: '删除成功' }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    } catch (error) {
      return new Response(JSON.stringify({ error: '删除记事本失败' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      })
    }
  }
} 